package middleware

import (
	"github.com/labstack/echo"
	"github.com/labstack/echo-contrib/session"
	"maki/model"
	"maki/utils"
)

func getUser(c echo.Context) (*model.User, error) {
	var user model.User
	v, err := session.Get("user", c)
	if err != nil {
		return nil, utils.ErrUserNotLogin
	}
	id := v.Values["ID"]
	userID, ok := id.(uint64)
	if !ok || userID <= 0 {
		return nil, utils.ErrUserNotLogin
	}
	if model.DB.First(&user, userID).RecordNotFound() {
		return nil, utils.ErrUserNotLogin
	}
	return &user, nil
}

// SetContextUser 给 context 设置 user
func SetContextUser(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		var user *model.User
		var err error
		if user, err = getUser(c); err == utils.ErrUserNotLogin {
			c.Set("user", nil)
			return next(c)
		}
		c.Set("user", user)
		return next(c)
	}
}

// SigninRequired 必须是登录用户
func SigninRequired(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		if u := c.Get("user"); u != nil {
			return next(c)
		}
		return utils.ErrUserNotLogin
	}
}

// AdminRequired 必须是管理员
func AdminRequired(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		if u := c.Get("user"); u != nil {
			if user, ok := u.(*model.User); ok {
				if user.IsAdmin() {
					return next(c)
				} else {
					return utils.ErrPermissionDenied
				}
			}
		}
		return utils.ErrUserNotLogin
	}
}
